package com.wdl.report.app.oss;

import android.content.Context;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;

import java.io.File;
import java.util.Random;

public class OssManager {
    /**
     * 图片上传的地址
     * 问后台要的
     */
    private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    /**
     * 图片的访问地址的前缀
     * 其实就是： bucketName + endpoint
     */
//    private static String prefix = "http://report-storage.oss-cn-beijing.aliyuncs.com/";
    private static String prefix = "http://timg.mxkj365.com/";
    /**
     * Bucket是OSS上的命名空间
     * 问后台要的
     */
    private static String bucketName = "report-storage";

    /**
     * 图片保存到OSS服务器的目录，问后台要
     */
    private static String dir = "report/";

    private OSS mOSS;

    private static OssManager mInstance;

    public static OssManager getInstance() {
        if (mInstance == null) {
            synchronized (OssManager.class) {
                mInstance = new OssManager();
            }
        }
        return mInstance;
    }

    public String upload(Context context, String filePath) {
        OSS oss = getOSS(context);
        //创建上传Object的Metadata
//                        ObjectMetadata objectMetadata = new ObjectMetadata();
//                        objectMetadata.setContentLength(instream.available());
//                        objectMetadata.setCacheControl("no-cache");
//                        objectMetadata.setHeader("Pragma", "no-cache");
//                        objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
//                        objectMetadata.setContentDisposition("inline;filename=" + fileName);

        File file=new File(filePath);
        if (!file.exists()){
            return null;
        }

        // 创建上传的对象
        PutObjectRequest put = new PutObjectRequest(bucketName,
                dir + getUUIDByRules32Image(), filePath);

        try {
            oss.putObject(put);
        } catch (ClientException e) {
            return null;
        } catch (ServiceException e) {
            return null;
        }

        return prefix + put.getObjectKey();
    }

    /**
     * 上传到后台的图片的名称
     */
    public static String getUUIDByRules32Image() {
        StringBuffer generateRandStr = null;
        try {
            String rules = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            int rpoint = 0;
            generateRandStr = new StringBuffer();
            Random rand = new Random();
            int length = 32;
            for (int i = 0; i < length; i++) {
                if (rules != null) {
                    rpoint = rules.length();
                    int randNum = rand.nextInt(rpoint);
                    generateRandStr.append(rules.substring(randNum, randNum + 1));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (generateRandStr == null) {
            return "getUUIDByRules32Image.pdf";
        }
        return generateRandStr + ".pdf";
    }

    /**
     * 创建OSS对象
     */
    private OSS getOSS(Context context) {
        if (mOSS == null) {
            OSSCredentialProvider provider = OSSConfig.newCustomSignerCredentialProvider();
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            mOSS = new OSSClient(context, endpoint, provider, conf);
        }
        return mOSS;
    }
}
